import moment from 'moment';
import { DiffOutlined, RollbackOutlined } from '@ant-design/icons';
import { useContext, useEffect, useMemo, useState } from 'react';
import { Button, Form, Spin, message, Input, Space, Badge } from 'antd';

import {
  downloadTemplate,
  getColorTextLoadMap,
  getFileNameByPath,
  getInvoiceCode,
  getPersonalInfo,
  getPosIDs,
  getTenantID,
  getUserDepName,
  getUserID,
  getUserName,
  newGetFileNameNotType,
} from '@/utils';
import MyIcon from '@/components/MyIcon';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Descriptions, useDescriptions } from '@/components/Descriptions';

import { updateCalibrateBtn } from '../mconfig';
import { IUpdateEnum } from '../common/UpdateReducer';
import { SourceUpdateContext } from '../common/UpdateContext';
import { DB_STATE, LB_STATE, YDB_STATE } from '../common/Format';
import { SHTG_CHECKSTATE, SHTH_CHECKSTATE, SHZ_CHECKSTATE } from '../../Acommon';
import { addCalibrateServices, applyBidService, editCalibrateServices, getCalibrateSerivice, syncApplyPackSerivice } from '../services/UpdateService';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { syncApplyStateService } from '../../DocumentationManage/services/UpdateService';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { updatePlanStateServices } from '../../ApplyManage/services/UpdateService';

/**
 * @UpdateSourceCalibrateView 定标组件
 * @returns
 */
const UpdateSourceCalibrateView = () => {
  const { Source_CurrentStep, Calibrate_Id, Invite_PackList, Source_Invite, curRes, Source_Calibrate, dispatch, locationProps } = useContext(
    SourceUpdateContext,
  );
  const { type } = locationProps?.state || {};
  const [cailbrateForm] = Form.useForm();

  /**撤销弹窗*/
  // const [invalidState, setInvalidState] = useState<Record<string, any>>({});

  const isOpen = useMemo(() => {
    if (Source_Calibrate && Source_Calibrate?.id) {
      if (
        Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1000` &&
        !Source_Calibrate?.checkState &&
        curRes?.['/purchaseSourceCalibrateController/addSourceCalibrate']
      ) {
        return true;
      } else if (
        Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1001` &&
        Source_Calibrate?.checkState == SHTH_CHECKSTATE() &&
        curRes?.['/purchaseSourceCalibrateController/editSourceCalibrate'] &&
        Source_Calibrate?.createrID == getUserID() &&
        Source_Calibrate?.createPositionID == getPosIDs()
      ) {
        return true;
      } else {
        return false;
      }
    } else {
      if (!Invite_PackList?.length) return false;
      const f = Invite_PackList?.every((item) => item?.state == DB_STATE() || item?.state == LB_STATE());
      return f && curRes?.['/purchaseSourceCalibrateController/addSourceCalibrate'];
    }
  }, [Source_Calibrate, Invite_PackList]);

  const [isPass, setIsPass] = useState(false);

  /** 审核中，审核通过开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);

  const [config, methods] = useDescriptions({
    name: 'source-calibrate',
    schemas: [
      {
        label: '定标申请',
        field: 'Title',
        component: 'Title',
      },

      {
        label: '采购项目名称',
        field: 'purchProjectName',
        component: 'Input',
        disabled: true,
      },
      {
        label: '流水单号',
        field: 'calibrateCode',
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
        initialValue: getInvoiceCode('DB'),
      },
      {
        label: '申请日期',
        field: 'calibrateTime',
        component: 'DatePicker',
        initialValue: moment(new Date(), 'YYYY-MM-DD'),
        required: true,
        disabled: true,
        message: '请选择申请日期',
      },
      {
        label: '承办人',
        field: 'ownerName',
        component: 'Input',
        message: '请输入承办人',
        disabled: true,
      },
      {
        label: '主办部门',
        field: 'ownDepartmentName',
        component: 'Input',
        message: '请输入主办部门',
        disabled: true,
      },
      {
        label: '联系电话',
        field: 'ownPhone',
        component: 'Input',
        message: '请输入联系电话',
        disabled: !isOpen,
      },
      {
        label: '拟办意见',
        field: 'opinionInfo',
        component: 'InputTextArea',
        maxLength: 200,
        initialValue: '请办公室、科创部、人事部、发展部及外联部负责人会签，请董安有同志审批。',
        showCount: true,
        colSpan: 2,
        autoSize: {
          minRows: 3,
          maxRows: 4,
        },
        message: '请输入拟办意见',
        disabled: !isOpen,
      },
      {
        label: '定标方式',
        field: 'calibrationMethod',
        component: 'Render',
        colSpan: 2,
        required: true,
        slotRender: (text) => {
          if (type == 'detail' || !isOpen) {
            return <span style={{ marginLeft: '8px' }}>{Number(text) == 0 ? '线上会签' : Number(text) == 1 ? '线下会议' : '--'}</span>;
          }

          return (
            <TagSelect
              colSpan={24}
              formLabel={''}
              formName={'calibrationMethod'}
              defalultKeys={Number(text)}
              // onChange={(val) => setIsPass(Boolean(val))}
              radioList={[
                {
                  value: 0,
                  name: '线上会签',
                },
                {
                  value: 1,
                  name: '线下会议',
                },
              ]}
              radioDisabled={!isOpen || Source_Calibrate?.checkState == SHTH_CHECKSTATE()}
            />
          );
        },
      },
      {
        label: '定标报告',
        field: 'attachURL',
        component: 'Render',
        colSpan: 2,
        slotRender: (text: string, record: Record<string, any>) => {
          const fileName = text ? getFileNameByPath(text) : '';
          if (type == 'detail' || !isOpen) {
            return (
              <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', padding: 10 }}>
                {fileName ? (
                  <>
                    <a
                      onClick={() => {
                        downloadTemplate('/purchaseNeedController/downloadFile', fileName, record?.attachURL, () => {});
                      }}
                    >
                      <MyIcon type="icon-file-text-fill" />
                      &nbsp;
                      {newGetFileNameNotType(fileName, 7)}
                    </a>
                  </>
                ) : (
                  <Input disabled={true} placeholder="--" />
                )}
              </div>
            );
          } else {
            return (
              <div style={{ paddingRight: 8 }}>
                <UploadFormCommon
                  form={cailbrateForm}
                  fileFormName={'attachURL'}
                  spanCol={24}
                  inRowProportion={24}
                  name={'attachFile'}
                  required={true}
                  accept={'.doc|.docx|.pdf'}
                  url={'/purchaseSourceCalibrateController/uploadFile'}
                  downloadUrl={'/purchaseSourceCalibrateController/downloadFile'}
                  fileFormDelName={'delLicenceUrl'}
                  delFunc={() => {}}
                  maxFile={1}
                  defaultFiles={text}
                  fieldBusiPath={'purchase/calibrate'}
                >
                  上传
                </UploadFormCommon>
              </div>
            );
          }
        },
        required: true,
        message: '请选择定标报告',
      },
    ],
    basicForm: cailbrateForm,
  });

  /** 保存定标详情 */
  const saveCalibrateDetail = (info: Record<string, any>) => {
    dispatch({
      type: IUpdateEnum.Set_Source_Calibrate,
      payload: info,
    });
  };

  /** 详情接口 */
  const { getCalibrateRun, getCalibrateLoading, reloadDetailInfo } = getCalibrateSerivice((res) => {
    if (res?.msgFlag) {
      saveCalibrateDetail(res?.obj);
      cailbrateForm?.setFieldsValue({
        ...res?.obj,
        calibrateTime: moment(res?.obj?.calibrateTime),
      });
    }
  });

  /** 刷新详情 */
  const reloadCalibrateDetail = (info: Record<string, any>) => {
    getCalibrateRun({ id: info?.id });
  };

  /** 编辑接口 */
  const { editCalibrateRun, editCalibrateLoading } = editCalibrateServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      getCalibrateRun({ id: res?.obj });
    } else {
      message.error(res?.msg);
    }
  });

  /** 暂存接口 */
  const { addCalibrateRun, addCalibrateLoading } = addCalibrateServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      getCalibrateRun({ id: res?.obj });
    } else {
      message.error(res?.msg);
    }
  });

  /** 修改计划状态,采购申请审批同意后-修改计划状态信息 执行中 */
  const { updatePlanStateRun, updatePlanStateLoading } = updatePlanStateServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
    } else {
      message.error(res.msg);
    }
  });

  /**同步申请【采购中】接口*/
  const { syncApplyStateRun, syncApplyStateLoading } = syncApplyStateService((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      // 同步修改计划状态
      const params = {
        calibrateID: Source_Calibrate?.id,
        applyID: null,
        state: `2`,
      };
      updatePlanStateRun(params);
    } else {
      message.error(res?.msg);
    }
  });

  // 定标线上 审批-最后一个人通过后调接口该状态
  const { syncApplyPackRun, syncApplyPackLoading } = syncApplyPackSerivice((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);

      // 同步修改申请状态
      syncApplyStateRun({
        calibrateID: Source_Calibrate?.id,
        state: `${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}1006`,
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 保存按钮 */
  const onSave = async () => {
    let { projectID, projectCode, projectName, projectSum, purchProjectName, purchProjectCode } = Source_Invite;
    const result = await methods?.validateFields();
    let resObj = {
      ...result,
      projectID,
      projectCode,
      projectName,
      projectSum,
      purchProjectName,
      purchProjectCode,
      sourceIDs:
        //开评标成功
        Invite_PackList?.map((item) => {
          if (item?.bidResult == 1) {
            return item?.id;
          }
        })?.join(','),
      calibrateTime: result?.calibrateTime && moment(result?.calibrateTime)?.format('YYYY-MM-DD HH:mm:ss'),
    };

    if (Source_Calibrate?.id && Source_Calibrate?.state) {
      // 编辑
      let editParams = {
        ...resObj,
        id: Source_Calibrate?.id,
        versionNum: Source_Calibrate?.versionNum,
      };
      editCalibrateRun(editParams);
    } else {
      // 新增
      let addParams = { ...resObj };
      addCalibrateRun(addParams);
    }
  };

  /** useEffect监听供应商报价数据中的定标ID */
  useEffect(() => {
    if (Calibrate_Id) {
      getCalibrateRun({ id: Calibrate_Id });
    } else {
      const packListRes = Invite_PackList?.filter((item) => item?.bidResult === null);
      if (packListRes?.length || !Invite_PackList?.length) {
        // 初始化表单
        cailbrateForm?.setFieldsValue({
          purchProjectName: Source_Invite?.purchProjectName,
          calibrateCode: getInvoiceCode('DB'),
          ownPhone: getPersonalInfo()?.phoneMobile,
          ownerName: getUserName(),
          ownDepartmentName: getUserDepName(),
          calibrateContent: '',
          calibrationMethod: 0,
        });
      } else {
        let str = `此次【${Invite_PackList?.[0]?.applyName}】中采用【${
          getColorTextLoadMap(Invite_PackList?.[0]?.procureRealName)?.colorText
        }】为拟采方式的标包，`;
        let CG_str: string[] = [];
        let SB_str: string[] = [];
        Invite_PackList?.forEach((item) => {
          if (item?.bidResult === 1) {
            CG_str?.push(item?.packCode);
          } else if (item?.bidResult === 0) {
            SB_str?.push(item?.packCode);
          }
        });
        str += CG_str?.join(',') ? CG_str?.join('，') + '招投标成功。' : '';
        str += SB_str?.join(',') ? SB_str?.join('，') + '招投标失败。' : '';

        cailbrateForm?.setFieldsValue({
          purchProjectName: Source_Invite?.purchProjectName,
          // purchProjectCode: Source_Invite?.purchProjectCode,
          calibrateCode: getInvoiceCode('DB'),
          ownPhone: getPersonalInfo()?.phoneMobile,
          ownerName: getUserName(),
          ownDepartmentName: getUserDepName(),
          calibrateContent: str,
        });
      }
    }
  }, [Calibrate_Id, Invite_PackList, Source_CurrentStep]);

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (
      Source_Calibrate?.state &&
      Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1001` &&
      Source_Calibrate?.checkState == SHZ_CHECKSTATE()
    ) {
      setIsSHTGFlag(true);
    }
    if (
      isSHTGFlag &&
      Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1002` &&
      Source_Calibrate?.checkState == SHTG_CHECKSTATE()
    ) {
      const idsList = Invite_PackList?.map((item: any) => {
        if (item?.bidResult == 1) {
          return item?.id;
        }
      });
      if (idsList?.length) {
        // 修改实施状态为已定标
        syncApplyPackRun({
          id: Source_Calibrate?.id,
          state: `${getTenantID()}${ILoadMapTypeAll?.CALIBRATE_STATE}1002`,
          sourceState: `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1014`,
        });
      }
    }
  }, [Source_Calibrate?.state, Source_Calibrate?.checkState, Invite_PackList]);

  /** 提交公告service */
  const { applyBidRun, applyBidLoading } = applyBidService((res: any) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 返回定标信息的表单 */
  const container = () => {
    return (
      <div className={'source-calibrate'}>
        <Spin
          spinning={
            addCalibrateLoading ||
            editCalibrateLoading ||
            getCalibrateLoading ||
            applyBidLoading ||
            syncApplyPackLoading ||
            syncApplyStateLoading ||
            updatePlanStateLoading
          }
        >
          <ScrollBarLayout>
            <div className={'source-calibrate-desc'}>
              <Badge.Ribbon
                text={
                  Source_Calibrate?.id && Source_Calibrate?.state != `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1000`
                    ? Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1001`
                      ? '审核中'
                      : Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1002`
                      ? '审核通过'
                      : Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1003`
                      ? '作废'
                      : '起草'
                    : '起草'
                }
                color={
                  Source_Calibrate?.id && Source_Calibrate?.state != `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1000`
                    ? Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1001`
                      ? '#F39C12'
                      : Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1002`
                      ? '#2ECC71'
                      : Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1003`
                      ? '#E74C3C'
                      : '#3498DB'
                    : '#3498DB'
                }
              >
                <Descriptions config={config} />
              </Badge.Ribbon>
            </div>
          </ScrollBarLayout>
        </Spin>
      </div>
    );
  };

  /** 澄清按钮权限 */
  const isShowBtn = useMemo(() => {
    if (Source_CurrentStep == 4) {
      return updateCalibrateBtn(curRes, Source_Calibrate, Invite_PackList);
    } else {
      return { calibrateSaveBtn: false };
    }
  }, [curRes, Source_Calibrate, Invite_PackList, Source_CurrentStep]);

  // 底部操作
  const btnFooter = () => {
    return (
      <Space>
        {isShowBtn?.calibrateSaveBtn && type != 'detail' && (
          <Button type="primary" onClick={onSave}>
            暂存
          </Button>
        )}
      </Space>
    );
  };

  return {
    UpdateSourceCalibrate: container,
    SourceCalibrateFooter: btnFooter,
    reloadCalibrateDetail,
  };
};

export default UpdateSourceCalibrateView;

{
  /* {invalidState?.isShow && (
          <RevokeModal
            resObj={invalidState?.resObj}
            revokeRequestUrl={'/purchaseSourceCalibrateController/invalid'}
            onClose={() => setInvalidState({})}
            reqBody={{ state: `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1000` }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.purchProjectName}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={() => reloadCalibrateDetail(invalidState?.resObj)}
          />
        )} */
}

{
  /* {curRes['/purchaseSourceCalibrateController/invalid'] &&
          Source_Calibrate?.id &&
          Source_Calibrate?.ownerID == getUserID() &&
          Source_Calibrate?.ownPositionID == getPosIDs() &&
          (Source_Calibrate?.state == `${getTenantID()}${ILoadMapTypeAll.CALIBRATE_STATE}1001` || Source_Calibrate?.checkState == SHTH_CHECKSTATE()) && (
            <Button
              type="primary"
              danger
              // icon={<RollbackOutlined />}
              onClick={() => {
                setInvalidState({ isShow: true, resObj: Source_Calibrate });
              }}
            >
              撤销
            </Button>
          )} */
}
